package com.example.smart_video.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Matrix
import android.graphics.SurfaceTexture
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Message
import android.text.TextPaint
import android.text.TextUtils
import android.util.Log
import android.view.Surface
import android.view.TextureView
import android.view.View
import android.view.WindowManager
import android.widget.SeekBar
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import com.danikula.videocache.HttpProxyCacheServer
import com.example.cleandemo3.R
import com.example.cleandemo3.databinding.ActivityVideoPlayBinding
import com.example.smart_video.ABpplication
import com.wink_172.library.AppManager
import com.wink_172.library.activity.SmartActivity
import com.wink_172.library.model.Constants
import com.wink_172.library.view.ActionBarView
import org.xutils.x
import java.io.IOException

/**
 * 仅仅是播放网络视频
 * 要用AppTheme.Activity03主题
 * 播放黑屏1   但有声音问题解决   initPlayVideo  之后要延迟800ms后才可以播放视频startPlayVideo     OPPO A59s黑屏问题就是这个引起的播放器还未初始化
 * 播放黑屏2   视频宽高超出屏幕大小很多 请调整视频大小
 * 播放黑屏3   切换视频必须要动态移除TextureView  动态增加TextureView  大概率是这个引起的
 * 播放黑屏3   视频长宽太大跟屏幕不匹配
 * 播放黑屏3   视频高清
 *
 * 2023年 大版本优化
 * 6.有声音没画面看surfaceCreated有没打印
 * 7.调用GONE或者INVISIBLE不会让TextureView调用onSurfaceTextureDestroyed，所以我们可以通过new对象的方式创建TextureView然后用父布局去addview和removeview   请参考VideoPlayActivity  ROOT模式
 * 8.去掉延迟播放 只要onSurfaceTextureAvailable回调即可播放   请参考VideoPlayActivity  ROOT模式
 * 9.去除重复initvideo
 * 10.换成"androidx.core:core-ktx:1.8.0"  之后视频播放器基本不会报错了
 * */
class VideoPlayActivity : SmartActivity(), TextureView.SurfaceTextureListener {
    lateinit var binding: ActivityVideoPlayBinding

    companion object {
        fun startActivity(context: Context, vararg args: Any) {
            val intent = Intent(context, VideoPlayActivity::class.java).apply {

                val mode = args[0] as Int    //mode    0简单播放

                when (mode) {
                    0 -> {
                        putExtra(Constants.PARAM_DATA1, mode)//mode
                        putExtra(Constants.PARAM_DATA2, args[1] as String)//视频url
                    }

                }

            }

            context.startActivity(intent)
        }

    }

    var sv_texture_w: Float = 0f
    var sv_texture_h: Float = 0f

    var mMediaPlayer: MediaPlayer? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBarLightMode()
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//保持屏幕常亮
        binding = DataBindingUtil.setContentView(this, R.layout.activity_video_play)
        binding.ivPlayIcon.setOnClickListener(this)
        binding.svTextureView.setOnClickListener(this)
        binding.svTextureView.surfaceTextureListener = this  //after

        initView()
        showProgressDialog(true)
        initVideo()//first
        init()
//        binding.svSureface.setRotationY(180f);//镜面对称
    }

    fun initVideo() {
        sv_texture_w = 0f

        // 创建一个MediaPlayer对象
        mMediaPlayer = MediaPlayer()

        mMediaPlayer?.setOnPreparedListener(MediaPlayer.OnPreparedListener {
//            if( mMediaPlayer?.videoWidth!!>900){//一般录像文件会比较大
//                mMediaPlayer?.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT)  //视频拉伸问题
//            }else{
//               mMediaPlayer?.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)  //视频拉伸问题
//            }
//            Log.e(TAG, "setOnPreparedListener: ====>>yyyy" )
            hideProgressDialog()
            mMediaPlayer?.start()
            binding.ivPlayIcon.visibility = View.INVISIBLE

            getHandle().sendEmptyMessage(com.example.smart_video.model.Constants.EventEnum.进度条更新.ordinal)
        })

        // 设置相关的监听器
        mMediaPlayer?.setOnCompletionListener(MediaPlayer.OnCompletionListener {
//          Log.e(TAG, "setOnCompletionListener: ===>>hello01:" + mMediaPlayer?.currentPosition)

            binding.ivPlayIcon.setVisibility(View.VISIBLE)//bug ID1010138


        })

        mMediaPlayer?.setOnBufferingUpdateListener(object : MediaPlayer.OnBufferingUpdateListener {
            override fun onBufferingUpdate(p0: MediaPlayer?, precent: Int) {//进度百分比
//                Log.e(TAG, "onBufferingUpdate: ====>>yyyy" + precent)
            }
        })


        mMediaPlayer?.setOnVideoSizeChangedListener(MediaPlayer.OnVideoSizeChangedListener { mediaPlayer, videoX, videoY ->

            if (sv_texture_w == 0f) {
                sv_texture_w = binding.svTextureView.getMeasuredWidth().toFloat()
                sv_texture_h = binding.svTextureView.getMeasuredHeight().toFloat()
//                m_surfaceView!!.setClipToOutline(true)//must
//                //TextureView设置视频圆角方式 代码哟用（保留-勿删）
//                m_surfaceView!!.setOutlineProvider(object : ViewOutlineProvider() {
//                    override fun getOutline(view: View, outline: Outline) {
//                        val rect = Rect(
//                            0, 0, m_surfaceView!!.getMeasuredWidth(),
//                            m_surfaceView!!.getMeasuredHeight()
//                        )
//                        outline.setRoundRect(rect, 0f)
//                    }
//                })
            }
            updateTextureViewSizeCenter(
                mMediaPlayer!!.videoWidth.toFloat(),
                mMediaPlayer!!.videoHeight.toFloat()
            )

        })
        mMediaPlayer?.setOnErrorListener(MediaPlayer.OnErrorListener { mediaPlayer, i, i1 ->

            false
        })
        mMediaPlayer?.setOnInfoListener(MediaPlayer.OnInfoListener { mediaPlayer, what, i1 ->
            when (what) {
                //701
                MediaPlayer.MEDIA_INFO_BUFFERING_START -> {
                    //开始卡顿-----需要做一些处理(比如：显示加载动画，或者当前下载速度) 开始缓冲(可理解为: 开始卡顿)
                    showProgressDialog(true)
//                    Log.e(TAG, "舞蹈加载中: ====>>yyyy" )

                }
                //702
                MediaPlayer.MEDIA_INFO_BUFFERING_END -> {
                    //卡顿结束   (隐藏加载动画，或者加载速度) 缓冲结束(可理解为: 卡顿结束)
//                    Log.e(TAG, "卡顿结束: ====>>yyyy" )
                    hideProgressDialog()
                }
                //3
                MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START -> {
//                 0  开始播放  用户只推第一帧视频渲染
                    hideProgressDialog()
//                    Log.e(TAG, "用户只推第一帧视频渲染: ====>>yyyy" )
                }

                //播放错误了 需要重新装载视频
                //804无法播放  Informs that audio is not playing. Note that playback of the video is not interrupted
                //805在小米机子出现过
                MediaPlayer.MEDIA_INFO_AUDIO_NOT_PLAYING,
                MediaPlayer.MEDIA_INFO_VIDEO_NOT_PLAYING -> {

                }

            }
            false
        })
        //播放时屏幕保持唤醒
        mMediaPlayer?.setScreenOnWhilePlaying(true)

    }

    fun init() {
        mode = intent.getIntExtra(Constants.PARAM_DATA1, 0) as Int;

        when (mode) {
            0 -> {
                var url: String? = intent.getStringExtra(Constants.PARAM_DATA2) as String?;

                if (TextUtils.isEmpty(url)) {
                    finish()
                } else {


                    x.task().postDelayed(Runnable {
                        startPlayVideo(url!!)
                    }, 300)

                }

            }


        }


    }


    fun initView() {

        binding.progress.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                // 当拖动条的滑块位置发生改变时触发该方法,在这里直接使用参数progress，即当前滑块代表的进度值

                if (mMediaPlayer != null) {
                    val allTime = mMediaPlayer!!.duration

                    val target = progress * allTime / 100;
                    if (fromUser) {//用于主动拖拽
                        mMediaPlayer!!.seekTo(target);
                    }
                }

            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })

        (binding.actionBar as ActionBarView).setBackground(null)
        (binding.actionBar as ActionBarView).setLineEnable(false)
        (binding.actionBar as ActionBarView).updateAllContent(
            R.mipmap.icon_back,
            " ",
            "编辑"
        );
        (binding.actionBar as ActionBarView).right_text.setTextColor(resources.getColor(R.color.white))
        val content_view =
            (binding.actionBar as ActionBarView).findViewById<TextView>(R.id.ac_content_view)
        val tp: TextPaint = content_view.getPaint()
        tp.setFakeBoldText(true)

        (binding.actionBar as ActionBarView).setCallback(object :
            ActionBarView.ICallback {
            override fun onSendEvent(event: Int, content: String?) {

                if (event == ActionBarView.LEFT_BTN) {
                    val upload_activity =
                        AppManager.appManager?.getActivity(UploadVideoActivity::class.java)
                    if (upload_activity != null) {
                        upload_activity.finish()
                    }
                    finish()

                } else if (event == ActionBarView.RIGHT_BTN) {
                    finish()
                }
            }
        })

    }

    /**
     * 暂停播放
     */
    private fun pausePlay() {
        if (mMediaPlayer != null) {
            mMediaPlayer!!.pause()
        }
    }

    /**
     * 恢复播放
     */
    private fun resumePlay() {
        if (mMediaPlayer != null) {
            mMediaPlayer!!.start()


        }
    }

    override fun onClick(v: View) {
        super.onClick(v)

        when (v.id) {
            R.id.sv_texture_view,
            R.id.iv_play_icon -> {

                if (mMediaPlayer != null) {
                    if (mMediaPlayer!!.isPlaying) {

                        binding.ivPlayIcon.setVisibility(View.VISIBLE)
                        pausePlay()

                    } else {

                        binding.ivPlayIcon.setVisibility(View.INVISIBLE)
                        resumePlay()
                    }
                }

            }
        }
    }


    override fun handlerCallBack(msg: Message?) {
        super.handlerCallBack(msg)
        when (msg!!.what) {
            com.example.smart_video.model.Constants.EventEnum.进度条更新.ordinal -> {
                try {

                    Log.e(TAG, "进度条更新: ====>>")
                    //java.lang.ArithmeticException: divide by zero
                    if (mMediaPlayer == null) {
                        return
                    }

                    if (mMediaPlayer != null && mMediaPlayer!!.duration > 0) {
                        val process =
                            (mMediaPlayer!!.currentPosition * 100) / mMediaPlayer!!.duration
                        binding.progress.progress = process

                    }
                } catch (e: Exception) {


                }

                getHandle().sendEmptyMessageDelayed(
                    com.example.smart_video.model.Constants.EventEnum.进度条更新.ordinal,
                    1000
                );
            }

        }
    }


    private val TAG = "VideoPlayActivity"


    /**重新计算video的显示位置，让其全部显示并据中
     *  Math.min
     * */
    private fun updateTextureViewSizeCenter(video_w: Float, video_h: Float) {
        val sx = sv_texture_w / video_w
        val sy = sv_texture_h / video_h
        val matrix = Matrix()
        val maxScale = Math.min(sx, sy);   //min   //min

        //第1步:把视频区移动到View区,使两者中心点重合.
        matrix.preTranslate((sv_texture_w - video_w) / 2, (sv_texture_h - video_h) / 2);

        //第2步:因为默认视频是fitXY的形式显示的,所以首先要缩放还原回来.
        matrix.preScale(video_w / sv_texture_w, video_h / sv_texture_h);

        //第3步,等比例放大或缩小,直到视频区的一边超过View一边, 另一边与View的另一边相等. 因为超过的部分超出了View的范围,所以是不会显示的,相当于不裁剪了.
        matrix.postScale(
            maxScale,
            maxScale,
            sv_texture_w / 2,
            sv_texture_h / 2
        );//后两个参数坐标是以整个View的坐标系以参考的


        binding.svTextureView.setTransform(matrix)
        binding.svTextureView!!.postInvalidate()
    }

    override fun onDestroy() {
        super.onDestroy()
        stopVideo()
        getHandle().removeMessages(com.example.smart_video.model.Constants.EventEnum.进度条更新.ordinal)
    }

    /**
     * 销毁
     */

    fun stopVideo() {
        if (mMediaPlayer != null) {
            mMediaPlayer?.stop()
            mMediaPlayer?.release()
            mMediaPlayer = null
        }
    }


    /**
     *url  网络地址
    注意不能传入本地路径，本地的你还传进来干嘛
    使用MediaPlayer.prepareAsync();，但是有时候会发生错误（-38,0）。最后查阅官方文档才发现当再Prepare的时候假如有stop（），start（），setDataSource(），seekTo(progress)，pause()，getCurrentPosition();等都会报错，所以要像中断操作只能使用reset（）方法。

    作者：AndyWei123
    链接：http://events.jianshu.io/p/c44ef00abdd6
    来源：简书
    著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
     * */
    private fun startPlayVideo(url: String) {
        // 设置播放的视频数据源
        try {
            val proxy: HttpProxyCacheServer = ABpplication.proxy!!
            val video_url = proxy.getProxyUrl(url)


            mMediaPlayer?.reset();
            mMediaPlayer?.setDataSource(video_url)
            mMediaPlayer?.isLooping = true

            // 播放准备，使用异步方式，配合OnPreparedListener
            mMediaPlayer?.prepareAsync()
        } catch (e: IOException) {
//            Toast.makeText(this, "视频地址错误", Toast.LENGTH_SHORT).show();
            e.printStackTrace()
        }


    }

    override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
        val surface = Surface(surface);
        mMediaPlayer!!.setSurface(surface)
    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
    }

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
        return true
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
    }

}